import { useEffect, useState, useRef } from 'react';

import styles from './index.module.scss';

export default props => {
    const initState = () => ({
        visible: false,
    });
    const [state, setState] = useState(initState);
    const container = useRef(null);

    useEffect(() => {
        const observer = new IntersectionObserver(([entry]) => {
            if(entry.isIntersecting) {
                setState(o => ({...o, visible: true}));
                observer.disconnect();
            }
        });

        if(container.current) observer.observe(container.current);

        return () => {
            if(container.current) observer.unobserve(container.current);
        };
    }, []);

    return (
        <div className={styles['container']} ref={container}>
            {state.visible ? props.children : null}
        </div>
    )
}
